<?php

namespace App\Http\Controllers\Common;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\AdminLog;
use App\Model\HomeLog;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;
use Lixunguan\Yuntongxun\Sdk as Yuntongxun;



class CommonController extends Controller
{

    /**
     * [json 以json格式响应]
     * @author LiYongHeng <[616649679@qq.com]>
     * @param  [int] $code [状态码]
     * @param  [string] $msg  [信息内容]
     * @param  array  $data [其他返回内容]
     * @return [object]       [j响应json数据]
     */
    public function json($code, $msg, $data = [])
    {
        return response()->json([
            'code' => $code,
            'msg'    => $msg,
            'data'  => $data,
        ]);
    }

    /**
     * [hasPower 检查路由是否有权限显示]
     * @author LiYongHeng <[616649679@qq.com]>
     * @param  [string]  $route [路由名称]
     * @return boolean        [存在返回真|否则为假]
     */
    public static function hasPower($route){

        //判断路由是否在权限范围内
        if (session('adminUser')['power'] != 'all') {
            $url =session('adminUser')['power'];
            if(strpos(','.$url.',',','.$route.',') === false){
                return false;
            }

        }
        return true;
    }

    /**
     * [admin_log 记录后台操作日志函数]
     * @author LiYongHeng <[616649679@qq.com]>
     * @param  [string] $user    [管理员名称]
     * @param  [int] $type    [类型]
     * @param  [string] $content [具体内容]
     * @return [bool]          [成功返回TRUE 否则返回false]
     */
    public function admin_log($user, $type, $content)
    {
        $str = "管理员：".$user;
        $time = time();
        // 执行添加记录
        $res = AdminLog::insertGetId([
            'username' => $str,
            'type' => $type,
            'content' => $content,
            'IP' => $_SERVER['REMOTE_ADDR'],
            'addtime' => $time,
            ]);
        // 判断是否添加成功
        if ($res) {
            return true;
        }
        return false;
    }

    /**
     * [home_log 记录前台操作日志]
     * @author LiYongHeng <[616649679@qq.com]>
     * @param  [string] $user    [用户名称]
     * @param  [int] $type    [类型]
     * @param  [string] $content [具体内容]
     * @return [bool]          [成功返回TRUE 否则返回false]
     */
    public function home_log($user, $type, $content)
    {
        $str = "用户".$user;
        $time = time();
        // 执行添加
        $res = HomeLog::insertGetId([
            'username' => $str,
            'type' => $type,
            'content' => $content,
            'IP' => $_SERVER['REMOTE_ADDR'],
            'addtime' => $time,
            ]);
        // 判断是否添加成功
        if ($res) {
            return true;
        }
        return false;
    }

    public function uploadToQiNiu(Request $request, $fileName = 'pic')
    {

        $file = $request->file($fileName);

        if(!$file){
            // $this->alertMess('没有上传文件');
            return false;
        }
        if(!$file->isValid()){
            $this->alertMess('上传文件不合法');
            return false;
        }

        // 需要填写你的 Access Key 和 Secret Key,具体查看七牛后台
        $accessKey = env('QINIU_ACCESSKEY');
        $secretKey = env('QINIU_SECRETKEY');

        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);


        // 要上传的空间,这是在你七牛后台设置的
        $bucket = env('QINIU_BUCKET');

        // 生成上传 Token
        $token = $auth->uploadToken($bucket);

        // 要上传文件的本地路径
        $filePath = $file->getRealPath();

        // 上传到七牛后保存的文件名
        $date = time().uniqid();
        $key = $date.'.'.$file->getClientOriginalExtension();

        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();

        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($res, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            // return ['status'=>4044,'msg'=>'失败', 'data' => $err];
            $this->alertMess('上传文件失败');
            return false;
        } else {
            // $info = [
            //   'status' => '2200',
            //   'msg'    => '上传成功',
            //   'data'   => $res
            // ];
            return $res;
        }
    }

    /**
     * 下载七牛云的数据,并添加限时token
     * @param $fileName     传入需要下载的文件名
     * @return string       返回链接字符串
     */
    public function downloadFile($fileName)
    {
        $auth = new Auth(env('ACCESS_KEY'),env('SECRET_KEY'));
        if(strpos($fileName,'http://') === false && strpos($fileName,env('QINIU_DOMAIN')) ===false){
            $baseUrl = 'http://'.env('QINIU_URL').env('QINIU_DOMAIN').'/'.$fileName;
            }else if (strpos($fileName,'http://') === false){
                $baseUrl = 'http://'.env('QINIU_URL').$fileName;
            }else{
                $baseUrl = env('QINIU_URL').$fileName;
            }
            $authUrl = $auth->privateDownloadUrl($baseUrl);
            return $authUrl;
    }

    /**
     * [alertMess js弹窗]
     * @author LiYongHeng <[616649679@qq.com]>
     * @param  string $mess [传入内容]
     * @return string       输出js脚步
     */
    public function alertMess($mess)
    {
        echo  "<script>alert('{$mess}')</script>";
    }

    /**
     * @CustomPagination 手动创建分页器
     * @author LiangZhi <gzphper@163.com>
     * @param  object $request  请求实例
     * @param  array $data      要分页的数据
     * @param  int   $perPage   每页显示条数
     * @return object 对数据分页后的分页对象
     */
    public static function CustomPagination(Request $request, $data, $perPage = 5)
    {

        $current_page = $request->input('page');
        $current_page = $current_page <= 0 ? 1 :$current_page;

        $item = array_slice($data, ($current_page-1)*$perPage, $perPage);
        $total = count($data);

        $paginator =new LengthAwarePaginator($item, $total, $perPage, $current_page, [
             'path' => Paginator::resolveCurrentPath(),
             'pageName' => 'page',
         ]);

        return $paginator;
    }
}
